﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    class MultiBinaryReader
    {
        public MultiBinaryReader(IEnumerable<byte[]> data)
        {
            memoryStreams = new Queue<MemoryStream>(Enumerable.Select(data, d => new MemoryStream(d)));
            GetNextReader();
        }

        private void GetNextReader()
        {
            _reader = new BinaryReader(memoryStreams.Dequeue());
        }

        private Queue<MemoryStream> memoryStreams;
        private BinaryReader _reader;

        public BinaryReader Reader
        {
            get { 
                Contract.Ensures(Contract.Result<BinaryReader>() != null);
                if (_reader.BaseStream.Position == _reader.BaseStream.Length)
                {
                    Contract.Assert(memoryStreams.Count > 0);
                    _reader = new BinaryReader(memoryStreams.Dequeue());
                    Debug.WriteLine("Dequeue");
                }
                return _reader;
            
            }
        }

        public ushort ReadUInt16()
        {
            return Reader.ReadUInt16();
        }

        public byte ReadByte()
        {
            return Reader.ReadByte();
        }

        public uint ReadUInt32()
        {
            return Reader.ReadUInt32();
        }

        public byte[] AttemptReadBytes(int length)
        {
            if (length == 0)
                return new byte[0];
            long remainingBytes = Reader.BaseStream.Length - Reader.BaseStream.Position;
            if (remainingBytes > length)
            {
                return Reader.ReadBytes(length);
            }
            return Reader.ReadBytes((int) remainingBytes);
        }
    }
}